package com.lmmob.autotest.uitest.controls;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

public class PagingToolbar extends Control {
    private final static String BUTTON_QUERY = ".query(\"[itemId='%s']\")[0].id";

    public PagingToolbar(WebDriver webDriver) {
        super(webDriver);
    }

    @Override
    protected String getSelfQuery() {
        return ".query(\"pagingtoolbar\")[0]";
    }

    public boolean prevPage() {
        return perform("prev");
    }

    public boolean nextPage() {
        return perform("next");
    }

    public boolean firstPage() {
        return perform("first");
    }

    public boolean lastPage() {
        return perform("last");
    }

    public boolean refresh() {
        return perform("refresh");
    }

    public Long currentPage() {
        return (Long) runScript("return " + this.getQuery() + ".query(\"textfield\")[0].value");
    }

    private boolean perform(String action) {
        String firstQuery = String.format("return " + this.getQuery() + BUTTON_QUERY, action);
        String firstId = (String) runScript(firstQuery);
        WebElement element = findElement(By.id(firstId)).findElement(By.tagName("button"));
        if (element != null && element.isEnabled()) {
            element.click();
            return true;
        } else
            return false;
    }

    protected String getName(){
        return "PagingToolbar";
    }
}
